package com.simple.mipc.handler;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.simple.mipc.entity.Executor;
import com.simple.mipc.messager.ExecutorManager;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MessageClientHandler extends Handler {

    public static final int RESULT_CODE = 4;

    public static final String FUNCTION_RES = "function_res";

    public static final String RESULT_DATA = "data";

    private static final Gson GSON = new Gson();

    @Override
    public void handleMessage(@NonNull Message msg) {
        Bundle bundle = msg.getData();
        int what = bundle.getInt("what");
        if (!Objects.equals(what, RESULT_CODE)) {
            log.warn("异常的结果");
        }
        String res = bundle.getString(FUNCTION_RES);
        String data = bundle.getString(RESULT_DATA);
        Map<String, String> map = GSON.fromJson(data, new TypeToken<HashMap<String, String>>() {
        }.getType());
        Executor executor = ExecutorManager.getInstance().get(res);
        if (Objects.isNull(executor)) {
            log.error("没有可以执行的回调");
            return;
        }
        assert executor != null;
        executor.execute(map);
    }
}
